package com.sam.im.heiqun.uis.activities;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.sam.im.heiqun.R;
import com.sam.im.heiqun.entities.RedPacketHistoryEntivity;
import com.sam.im.heiqun.entities.RedPacketUserEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.adapters.RedPackageDetailsAdapter;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.GlideUtils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 红包详细
 */
public class RedPackageDetailsActivity extends BaseSwipeBackActivity {

    @BindView(R.id.head_img)
    ImageView headImg;

    @BindView(R.id.nick_name)
    TextView nickName;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.already_get_count)
    TextView alreadyGetCount;

    @BindView(R.id.recycler_view)
    RecyclerView mListView;
    @BindView(R.id.activity_red_package_details)
    RelativeLayout activityRedPackageDetails;
    @BindView(R.id.text_view)
    TextView textView;
    @BindView(R.id.scroll_view)
    ScrollView scrollView;
    @BindView(R.id.pre_v_back)
    ImageView preVBack;
    @BindView(R.id.pre_tv_title)
    TextView preTvTitle;
    @BindView(R.id.right)
    ImageView right;
    @BindView(R.id.red_bag)
    TextView redBag;
    @BindView(R.id.txt_pin)
    TextView txt_pin;
    @BindView(R.id.isget)
    TextView tvisget;
    @BindView(R.id.tv_no_open_permission)
    TextView tvNoOpenPermission;
    private List<RedPacketUserEntivity> redPacketUserEntivities = new ArrayList<>();
    private RedPackageDetailsAdapter adapter;
    private PGService mPgService;

    private int type = 0;   //0-私聊；1-群聊
    private RedPacketHistoryEntivity redPacketHistoryEntivity;
    private String status;

    @Override
    public int getContentViewId() {
        return R.layout.activity_red_package_details;
    }

    @Override
    protected String getTitleText() {
        return getResources().getString(R.string.red_packet_details);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        mPgService = PGService.getInstance();
        setWindowStatusBarColor(this, R.color.red9);
        type = getIntent().getIntExtra("type", 0);
        redPacketHistoryEntivity = (RedPacketHistoryEntivity) getIntent().getSerializableExtra("redPacketId");
        status = getIntent().getStringExtra("status");
        // String redPacketId = getIntent().getStringExtra("redPacketId");
        adapter = new RedPackageDetailsAdapter(this);
        mListView.setLayoutManager(new LinearLayoutManager(this));
        mListView.setAdapter(adapter);
        long userId = ToolsUtils.getUser().getId();
        getRedPacketHistory();
        scrollView.scrollTo(0, 0);
        redBag.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(MyWalletDetailsActivity.class);
            }
        });
        if("1".equals(status)){
            tvNoOpenPermission.setVisibility(View.VISIBLE);
        }else {
            tvNoOpenPermission.setVisibility(View.GONE);
        }
    }

    /**
     * 获取红包历史记录
     */
    private void getRedPacketHistory() {
        GlideUtils.loadHeadCircularImage(RedPackageDetailsActivity.this, redPacketHistoryEntivity.getRedPacket().getHeadUrl(), headImg);
        redPacketUserEntivities.addAll(redPacketHistoryEntivity.getRedPacketHistory());
        if (0 == type) {//单聊
            /** 由于服务器中的状态值State不准确，只能用这种方式 */
            if (null == redPacketUserEntivities || redPacketUserEntivities.size() == 0) {//如果领取记录中没有数据，说明未领取
                if ("1".equals(redPacketHistoryEntivity.getRedPacket().getStatus())) {
                    alreadyGetCount.setText(getString(R.string.red_package_money) + redPacketHistoryEntivity.getRedPacket().getRedPacketAmount() +
                            getString(R.string.yuan_wait_other_receive));
                    money.setVisibility(View.GONE);
                    redBag.setVisibility(View.GONE);
                } else {
                    alreadyGetCount.setText(getString(R.string.red_package_money) + redPacketHistoryEntivity.getRedPacket().getRedPacketAmount() +
                            getString(R.string.yuan_already_overtime_back));
                    money.setVisibility(View.GONE);
                    redBag.setVisibility(View.GONE);
                }
            } else {//已经领取
                alreadyGetCount.setText(getString(R.string.one_red_package_common) + redPacketHistoryEntivity.getRedPacket().getRedPacketAmount() +
                        getString(R.string.yuan));
                if (redPacketHistoryEntivity.getRedPacket().getUserId().equals("" + ToolsUtils.getMyUserId())) {//我发的
                    money.setVisibility(View.GONE);
                    //redBag.setVisibility(View.GONE);
                    tvisget.setVisibility(View.GONE);
                } else {
                    money.setText(redPacketHistoryEntivity.getRedPacket().getRedPacketAmount());//我领的
                    money.setVisibility(View.VISIBLE);
                    redBag.setVisibility(View.VISIBLE);
                    tvisget.setVisibility(View.VISIBLE);
                }
            }
        } else {//群聊
            /** 由于服务器中的状态值State不准确，只能用这种方式 */

            String redNum = redPacketHistoryEntivity.getRedPacket().getRedPacketCount();//总红包个数
            int getNum = null == redPacketUserEntivities ? 0 : redPacketUserEntivities.size();//已经抢的人数
            double summoney = Double.parseDouble(redPacketHistoryEntivity.getRedPacket().getRedPacketAmount());//红包总金额 ;
            if (redPacketHistoryEntivity.getRedPacket().getRedPacketType().equals("1")) {
                txt_pin.setVisibility(View.VISIBLE);//手气最佳
            }
            double qiang = 0;//当前一共抢完的金额
            double thiszzz = 0;//当前最高的金额
            int zzz = 0;//当前最高的下标
            boolean isMyGet = false;//当前列表中，是否存在我，如果存在说明我已抢过
            if (null != redPacketUserEntivities && getNum > 0) {//循环查询我抢的金额，并计算金额最高
                for (int i = 0; i < getNum; i++) {
                    if (redPacketUserEntivities.get(i).getUserId().equals("" + ToolsUtils.getMyUserId())) {
                        money.setText(redPacketUserEntivities.get(i).getAmount());//设置我抢到的金额
                        isMyGet = true;
                    }
                    qiang = qiang + Double.parseDouble(redPacketUserEntivities.get(i).getAmount());//当前抢到总额
                    if (thiszzz < Double.parseDouble(redPacketUserEntivities.get(i).getAmount())) {
                        //更新目前抢到的最高金额信息
                        thiszzz = Double.parseDouble(redPacketUserEntivities.get(i).getAmount());
                        zzz = i;
                    }
                }
            }
            if (null == redPacketUserEntivities || redPacketUserEntivities.size() < Integer.parseInt(redNum)) {
                //没抢光
                if (redPacketHistoryEntivity.getRedPacket().getUserId().equals("" + ToolsUtils.getMyUserId())) {//我是发包人
                    // redBag.setVisibility(View.GONE);

                    if ("1".equals(redPacketHistoryEntivity.getRedPacket().getRedPacketType())) {//拼手气红包
                        double count = summoney - qiang;
                        DecimalFormat df = new DecimalFormat("0.00");
                        String countStr = String.valueOf(df.format((count)));
                        alreadyGetCount.setText(getResources().getString(R.string.already_receive) + getNum + "/" + redNum + getString(R.string.entrie_common) + summoney
                                + getString(R.string.yuan_surplus) + countStr + getString(R.string.yuan));
                    } else {//普通红包
                        double count = (summoney * Integer.parseInt(redNum)) - qiang;
                        DecimalFormat df = new DecimalFormat("0.00");
                        String countStr = String.valueOf(df.format((count)));
                        alreadyGetCount.setText(getResources().getString(R.string.already_receive) + getNum + "/" + redNum + getString(R.string.entrie_common) + (summoney * Integer.parseInt(redNum))
                                + getString(R.string.yuan_surplus) + countStr + getString(R.string.yuan));
                    }
                } else {
                    redBag.setVisibility(View.VISIBLE);
                    alreadyGetCount.setText(getResources().getString(R.string.already_receive) + getNum + "/" + redNum + getString(R.string.entrie));
                }
            } else {//已抢光
                if (redPacketHistoryEntivity.getRedPacket().getUserId().equals("" + ToolsUtils.getMyUserId())) {//我是发包人
                    // redBag.setVisibility(View.GONE);
                    long titme = Long.parseLong(redPacketHistoryEntivity.getTime());
                    if ("1".equals(redPacketHistoryEntivity.getRedPacket().getRedPacketType())) {//拼手气红包
                        alreadyGetCount.setText(redNum + getString(R.string.entrie_red_package_common) + summoney + getString(R.string.yuan) + "，" + ToolsUtils.getTimeString(titme) + getString(R.string.kill_and_loot));
                    } else {//普通红包
                        alreadyGetCount.setText(redNum + getString(R.string.entrie_red_package_common) + (summoney * Integer.parseInt(redNum)) + getString(R.string.yuan) + "，" + ToolsUtils.getTimeString(titme) + getString(R.string.kill_and_loot));
                    }
                } else {
                    redBag.setVisibility(View.VISIBLE);
                    long titme = Long.parseLong(redPacketHistoryEntivity.getTime());
                    alreadyGetCount.setText(redNum + getString(R.string.entrie_red_package) + ToolsUtils.getTimeString(titme) + getString(R.string.kill_and_loot));
                }
                if ("1".equals(redPacketHistoryEntivity.getRedPacket().getRedPacketType())) {//拼手气红包才会有手气最佳
                    if (null != redPacketUserEntivities && getNum > 0) {
                        for (int i = 0; i < getNum; i++) {
                            if (i == zzz) {
                                RedPacketUserEntivity mmm = redPacketUserEntivities.get(i);
                                mmm.setIsZui("1");
                                redPacketUserEntivities.set(i, mmm);
                            }
                        }
                    }
                }
            }
            if (isMyGet) {//判断我是否有领取红包
                redBag.setVisibility(View.VISIBLE);
                tvisget.setVisibility(View.VISIBLE);
            } else {
                tvisget.setVisibility(View.GONE);

            }
        }
        String name = "";
        if (ToolsUtils.isMyFriendForId(Long.parseLong(redPacketHistoryEntivity.getRedPacket().getUserId()))) {
            name = ToolsUtils.getNick(ToolsUtils.getFriendById(redPacketHistoryEntivity.getRedPacket().getUserId()));
        } else {
            name = redPacketHistoryEntivity.getRedPacket().getName();
        }
        nickName.setText(name);
        textView.setText(redPacketHistoryEntivity.getRedPacket().getRedPacketContent());
        adapter.refresh(redPacketUserEntivities);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
